<?php

// define('code_success', 0);
// define('code_custom_error', 500);

class UserStatus {
	
	/* 
	 * 检查用户当前状态
	 */
	public static function get($userName) {
		
		$userStatusModel = D('user_status');
		$where['userName'] = $userName;
		$user = $userStatusModel->where($where)->find();
//		Log::write($userStatusModel->getLastSql());
		if (!isset($user)) {
			return NULL;
		}
		
		return (object)$user;
	}

	/*
	 * 创建用户当前状态
	*/
	public static function create($userName, $materialId) {
		return (object)array('userName' => $userName, 
				'materialId' => $materialId,
				'onReady' => 0, 
				'status' => NULL,
				'reserve1' => NULL,
				'reserve2' => NULL,
				'reserve3' => NULL,
				'reserve4' => NULL,
				'reserve5' => NULL
		 );
	}
	
	/*
	 * 更新用户状态
	 */
	public static function update($userStatus) {

		$userStatusModel = M('user_status');
		
		$user = UserStatus::get($userStatus->userName);
		if (isset($user)) {
			$data = array('materialId' => $userStatus->materialId, 
					'lastPostTime' => date('Y-m-d H:i:s'),
					'onReady' => $userStatus->onReady,
					'status' => $userStatus->status,
					'reserve1' => $userStatus->reserve1,
					'reserve2' => $userStatus->reserve2,
					'reserve3' => $userStatus->reserve3,
					'reserve4' => $userStatus->reserve4,
					'reserve5' => $userStatus->reserve5
			);
			
			$where['id'] = $user->id;
			$userStatusModel->where($where)->save($data);
//			Log::write($userStatus->userName.$userStatusModel->getLastSql());
		} else {
			$userStatusModel->create();
			$userStatusModel->userName = $userStatus->userName;
			$userStatusModel->materialId = $userStatus->materialId;
			$userStatusModel->lastPostTime = date('Y-m-d H:i:s');
			$userStatusModel->onReady = $userStatus->onReady;
			$userStatusModel->status = $userStatus->status;
			$userStatusModel->reserve1 = $userStatus->reserve1;
			$userStatusModel->reserve2 = $userStatus->reserve2;
			$userStatusModel->reserve3 = $userStatus->reserve3;
			$userStatusModel->reserve4 = $userStatus->reserve4;
			$userStatusModel->reserve5 = $userStatus->reserve5;
			$userStatusModel->add();
		}
	}
	
	/* 
	 * 设置用户开始启动连续处理状态
	 */
	public static function begin($userStatus) {
		$userStatus->onReady = 0;//开始连续处理
		UserStatus::update($userStatus);
	}
	
	/* 
	 * 设置用户结束处理状态
	*/
	public static function end($userStatus) {
		$userStatus->onReady = 1;//开始连续处理
		UserStatus::update($userStatus);
	}
}